package webcert.ch03.ex0302;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

//@WebServlet(name = "AttributesAllScopes", urlPatterns = "/AttributesAllScopes")
public class AttributesAllScopes extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();

        request.getSession().setAttribute("mySessionAttribute", "mySessionValue");
        request.setAttribute("myRequestAttribute", "myRequestValue");

        out.write("Request scope:");
        Enumeration<String> requestAttributes = request.getAttributeNames();
        while (requestAttributes.hasMoreElements()) {
            String attributeName = requestAttributes.nextElement();
            out.write("\nAttribute name: " + attributeName);
            out.write("\nAttribute value: " + request.getAttribute(attributeName));

        }

        out.write("\n\nSession scope:");
        HttpSession session = request.getSession();
        Enumeration<String> sessionAttributes = session.getAttributeNames();
        while (sessionAttributes.hasMoreElements()) {
            String attributeName = sessionAttributes.nextElement();
            out.write("\nAttribute name: " + attributeName);
            out.write("\nAttribute value: " + session.getAttribute(attributeName));

        }

        out.write("\n\nContext scope:");
        Enumeration<String> contextAttributes = getServletContext().getAttributeNames();
        while (contextAttributes.hasMoreElements()) {
            String attributeName = contextAttributes.nextElement();
            out.write("\nAttribute name: " + attributeName);
            out.write("\nAttribute value: " + getServletContext().getAttribute(attributeName));

        }
    }
}
